from flask import Flask, render_template
import requests
from bs4 import BeautifulSoup

app = Flask(__name__)


@app.route('/')
def index():
    try:
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36"
        }
        url = "https://movie.douban.com/"
        response = requests.get(url, headers=headers)

        # 解析 HTML 内容
        soup = BeautifulSoup(response.text, 'html.parser')
        print(soup)

        # 提取所有带有 data-title 属性的标签
        elements_with_data_title = soup.find_all(attrs={"data-title": True})

        # 获取前几个标题和链接
        movies = []
        for element in elements_with_data_title[:5]:
            title = element.get('data-title')
            link = element.get('href') or '#'
            movies.append({'title': title, 'link': link})

        return render_template('index.html', movies=movies)

    except Exception as e:
        return f"Error occurred: {str(e)}"


if __name__ == '__main__':
    app.run(debug=True, port=4050)
